const app = getApp()
Page({
  data: {
    username: '',
    files: [],
    imgTmpPath: ''
  },
  onLoad() {
    this.setData({
      selectFile: this.selectFile.bind(this),
      username: app.globalData.userInfo.username,
      imgTmpPath: app.globalData.userInfo.avatarUrl
    })
  },
  // 选择图片
  selectFile (image) {
    const regImg = /(\.jpg|\.jpeg|\.gif|\.png)$/
    let isImg = regImg.test(image.tempFilePaths[0])
    if (isImg) {
      this.setData({
        imgTmpPath: image.tempFilePaths[0]
      })
    }
    return isImg
  },
  // 图片预览
  previewImage: function(e){
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.imgTmpPath // 需要预览的图片http链接列表
    })
  },
  // 双向绑定 username
  handleInput (e) {
    this.setData({
      username: e.detail.value
    })
  },
  // 删除图片
  handleDelete () {
    this.setData({
      imgTmpPath: ''
    })
  },
  // 提交用户信息
  async handleSummit () {
    const regImg = /(\.jpg|\.jpeg|\.gif|\.png)$/
    const imgType = regImg.exec(this.data.imgTmpPath)
    if (!this.data.username) {
      wx.showModal({
        title: '警告',
        content: '昵称不能为空！'
      })
    } else if (!this.data.imgTmpPath) {
      wx.showModal({
        title: '警告',
        content: '头像不能为空！'
      })
    }
    wx.showLoading({
      title: '信息上传中...',
      mask: true
    })
    // 判断是否为临时地址，用户不选的话可能是网络地址
    const reg = /^(http:\/\/tmp|wxfile:\/\/tmp)/
    if (reg.test(this.data.imgTmpPath)) {
      // 没有修改过头像，就不需要上传
      const response = await wx.cloud.uploadFile({
        cloudPath: `./images/avatars/${Date.now()}${imgType[0]}`,
        filePath: this.data.imgTmpPath
      })
      if (response.fileID) {
        const { result } = await wx.cloud.callFunction({
          name: 'editMyInfo',
          data: {
            username: this.data.username,
            avatarId: response.fileID
          }
        })
        app.globalData.userInfo.username = result.username
        app.globalData.userInfo.avatarUrl = result.avatarUrl
        wx.showToast({
          title: '修改成功！',
          icon: 'success'
        })
      }
    } else {
      // 只修改名字即可
      const { result } = await wx.cloud.callFunction({
        name: 'editMyInfo',
        data: {
          username: this.data.username
        }
      })
      app.globalData.userInfo.username = result.username
      wx.showToast({
        title: '修改成功！',
        icon: 'success',
        success () {
          wx.navigateBack({
            delta: 1
          })
        }
      })
    }
  }
})